<template>
  <div id="faceLogin" class="app-container">
    <!-- 人脸绑定 or 识别 -->
    <div id="mainDiv" ref="mainDiv">
      <video id="video" width="500px" height="500px" autoplay="autoplay" muted="muted" style="margin-top: 20px" />
      <canvas id="canvas" width="500px" height="500px" />
    </div>
    <div style="margin: 30px auto;text-align: center">
      <el-button v-if="typeBoolean" :disabled="isDisable" type="primary" @click="takePhoto">绑定</el-button>
      <el-button v-else :disabled="isDisable" type="danger" @click="chooseFileChangeComp">人脸登录</el-button>
    </div>
  </div>
</template>

<script>
import { faceAdd } from '@/api/face/face'
import { hideFullScreenLoading, showFullScreenLoading } from '@/utils/loadIng'

export default {
  name: 'Face',
  props: {
    // 当前登录用户信息
    userInfo: {
      type: Object,
      default: () => {
      }
    },
    // 类型
    typeBoolean: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isDisable: false,
      count: 6,
      mediaStreamTrack: null
    }
  },
  mounted() {
    this.getMedia()
    this.$nextTick(() => {
      this.loadTraining()
    })
  },
  destroyed() {
    this.closeVideo()
  },
  methods: {
    // 关闭摄像头
    closeVideo() {
      if (this.mediaStreamTrack) {
        console.log(this.mediaStreamTrack)
        console.log(this.mediaStreamTrack.getTracks())
        this.mediaStreamTrack.getTracks()[0].stop()
        this.mediaStreamTrack.getTracks()[1].stop()
      }
    },
    // 获取摄像头
    getMedia() {
      const constraints = {
        video: { width: 500, height: 500 },
        audio: true
      }
      // 获得video摄像头区域
      const video = document.getElementById('video')
      // 这里介绍新的方法，返回一个 Promise对象
      // 这个Promise对象返回成功后的回调函数带一个 MediaStream 对象作为其参数
      // then()是Promise对象里的方法
      // then()方法是异步执行，当then()前的方法执行完后再执行then()内部的程序
      // 避免数据没有获取到
      const promise = navigator.mediaDevices.getUserMedia(constraints)
      promise.then((MediaStream) => {
        video.srcObject = MediaStream
        video.play()
        console.log('打开')
        this.mediaStreamTrack = MediaStream
      })

      // 定时任务
      // let time = setInterval(() => {
      //   this.count -= 1
      //   if (this.count <= 0) {
      //     // 三十秒倒计时
      //     this.$emit('dialogVisibleFace')
      //     // 销毁
      //     clearInterval(time)
      //   }
      // }, 1000)
    },
    // 人脸识别拍照
    takePhoto() {
      this.isDisable = true
      // 获得Canvas对象
      const video = document.getElementById('video')
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, 500, 500)
      var base64File = canvas.toDataURL()
      const data = {
        file: base64File,
        name: this.userInfo.name,
        groupId: '101'
      }
      faceAdd(data).then(res => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          console.log(res)
        } else {
          this.msgError(res.msg)
        }
        this.isDisable = false
      }).catch(error => {
        console.log('绑定人脸错误', error)
        this.isDisable = false
      })
    },
    // 人脸对比
    chooseFileChangeComp() {
      this.isDisable = true
      this.dialogVisible = false
      showFullScreenLoading('#faceLogin')
      const video = document.getElementById('video')
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, 500, 500)
      var base64File = canvas.toDataURL()
      // 开始登陆请求
      this.$store.dispatch('user/faceSearch', {
        file: base64File,
        groupId: '101'
      }).then(() => {
        hideFullScreenLoading()
        this.isDisable = false
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      }).catch((error) => {
        console.log(error)
        this.isDisable = false
        hideFullScreenLoading()
      })
    },
    // 人脸追踪
    loadTraining() {
      const video = document.getElementById('video')
      const canvas = document.getElementById('canvas')
      const context = canvas.getContext('2d')

      // eslint-disable-next-line no-undef
      var tracker = new tracking.LandmarksTracker()
      console.log(tracker)
      tracker.setInitialScale(4)
      tracker.setStepSize(2)
      tracker.setEdgesDensity(0.1)
      // eslint-disable-next-line no-undef
      tracking.track(video, tracker)

      tracker.on('track', function(event) {
        context.clearRect(0, 0, canvas.width, canvas.height)
        if (!event.data) return
        event.data.faces.forEach(function(rect) {
          context.strokeStyle = '#eb4c4c'
          context.strokeRect(rect.x, rect.y, rect.width, rect.height)
          context.font = '16px Helvetica'
          context.fillStyle = '#fbfbfb'
          context.lineWidth = '5'
          context.fillText('人脸横向: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11)
          context.fillText('人脸纵向: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 50)
        })
        /**
         * 人脸追踪 颗粒
         */
        event.data.landmarks.forEach(function(landmarks) {
          for (var l in landmarks) {
            context.beginPath()
            context.fillStyle = '#fff'
            context.arc(landmarks[l][0], landmarks[l][1], 3, 0, 1 * Math.PI)
            context.fill()
          }
        })
      })
    }
  }
}
</script>

<style scoped>
#mainDiv {
  width: 100%;
  height: 530px;
  position: relative;
  background: #eee;
  overflow: hidden;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}

video, canvas {
  position: absolute;
}

</style>
